<?php
/**
 * Common functions over all clases
 * 
 * @author Aurelijus Banelis
 */

/* Debug settings */
define("DEBUG_MODE", true);

/* Messages */
$error_messages = Array();
$warning_messages = Array();
$success_messages = Array();
$other_messages = Array();
function add_error($msg){
    global $error_messages;
    array_push($error_messages, $msg);
}
function add_warning($msg){
    global $warning_messages;
    array_push($warning_messages, $msg);
}
function add_success($msg){
    global $success_messages;
    array_push($success_messages, $msg);
}
function add_other_message($msg){
    global $other_messages;
    array_push($other_messages, $msg);
}

/* Error handling */
function error($errno, $error_message, $filename, $linenum, $vars) {
    if (!defined("DEBUG_MODE")) {
        //TODO: in production mode mailing or logging to file
        return;
    }
    
    $white_list = array('settings.php)', 'mysql_connect()');
    foreach($white_list as $item) {
        if (strpos($error_message, $item) !== false) {
            return;
        }
    }
    
    if (includePathCheck($error_message)) {
        return;
    }    
    $error_type = array (
        E_ERROR             => "Error",
        E_WARNING           => "Warning",
        E_PARSE             => "Parsing Error",
        E_NOTICE            => "Notice",
        E_CORE_ERROR        => "Core Error",
        E_CORE_WARNING      => "Core Warning",
        E_COMPILE_ERROR     => "Compile Error",
        E_COMPILE_WARNING   => "Compile Warning",
        E_USER_ERROR        => "User Error",
        E_USER_WARNING      => "User Warning",
        E_USER_NOTICE       => "User Notice",
        E_STRICT            => "Runtime Notice",
        E_RECOVERABLE_ERROR => "Recoverable Error"
    );
    if (array_key_exists($errno, $error_type)) {
        $error_type = $error_type[$errno];
    } else {
        $error_type = 'Unknown error';
    }
    
    $error_message = nl2br(htmlspecialchars($error_message));
    $text = "<div style='background: #880000; color: white'>$error_type <b>$error_message</b>. Backtrace:<ol>";
    foreach (debug_backtrace() as $info) {
        if (array_key_exists('file', $info)) {
            $file = htmlspecialchars($info['file']);
            $line = intval($info['line']);
            $function = $info['function'] ? "in function <b>{$info['function']}()</b>" : "";
            $text .= "<li><b>$file</b>:$line $function";
            if (array_key_exists('args', $info)) {
                $text .= ' Arguments:<pre><small>';
                $args = $info['args'];
//                if (is_array($info['args']) && count($info['args']) > 10) {
                    if (is_array($args) && is_array(current($args))) {
                        $text .= "<i>Array of array " . count($args) . "x"  . count(current($args)) . ' elements</i>';
                    } else {
//                        var_dump($info['args']);
						$text .= print_r($info['args'], true);
                    }
//                } else {
//                    var_dump($info['args']);
//                }
                $text .= '</small></pre>';
            } else {
                $args = '';
            }
            $text .= '</li>';
        }
    }
    $text .= '</ol></div>';
    $msg1 = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
			<html>
			<head>
				<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
			</head>
			<body>';
			$msg2 = '</body>
			</html>';
    //FIXME: do not use in production environment
    $header = "From: aurelijus@wapsite.lt\n";
    $header .= "Content-type: text/html; charset=utf-8\n";
//    @mail('gramasoft@googlegroups.com', 'Klaida GRAMAsoft sistemoje', $msg1 . $text . $msg2, $header);
    echo $text;    
    echo '<div style="background: #880000; color: white;">Įvyko nenumatyta sisteminė klaida. Projekto kūrėjai informuoti el. paštu ir klaida jau pradėta taisyti. Atsiprašome už sukeltus nepatogumus.</div>';
}

$old_error_handler = set_error_handler('error');
error_reporting(E_ALL | E_STRICT);

function includePathCheck($error_name) {
    if (preg_match("/(require_once|inlude_once|require|include)\((.+)\).+/", $error_name, $mathes)) {
        $root_directory = dirname(__FILE__);
        $expexted = $mathes[2];
        $pathFix = $root_directory . DIRECTORY_SEPARATOR . basename($expexted);
        if (file_exists($pathFix)) {
            require $pathFix;
            return true;
        }
    }
}

/**
 * Helper for parsing request and formating links
 */
class Addresing {
    
    /**
     * Parse request and extracts tab part
     */
    public static function get_requested_tab() {
        if (array_key_exists('tab', $_GET)) {
            return $_GET['tab'];
        } else {
            $command_start = strpos($_SERVER['REQUEST_URI'], '?');
            if ($command_start !== FALSE) {
                return substr($_SERVER['REQUEST_URI'], $command_start + 1);
            } else {
                return '';
            }
        }
    }
    
    public static function isPrintVersion($tabs, &$file) {
        if (array_key_exists('version', $_GET) && $_GET['version'] == 'print') {
            $tab = self::get_requested_tab();
            if (array_key_exists($tab, $tabs)) {
                $file = 'GUI/' . dirname($tabs[$tab]) . '/print_version.php';
                return file_exists($file);
            }
        }
        return false;
    }
    
    public static function get_load_view_parameters(&$tab, &$load, &$sort_by) {
        switch (self::get('load')) {
            case 'is':
                $load = 'is';
                break;
            default:
                $load = 'subdivision';
        }
        switch (self::get('sort_by')) {
            case 'time':
                $sort_by = 'time';
                break;
            default:
                $sort_by = 'quantity';
        }
        $tab = self::get_requested_tab();
    }
   
    /**
     * @return String   parameter from $_GET;
     */
    public static function get($key) {
        if (array_key_exists($key, $_GET)) {
            return $_GET[$key];
        } else {
            return null;
        }
    }
}

/* Date */
date_default_timezone_set('Europe/Vilnius');
